<!-- 全局数据建模页面 -->
<template>
  <div class="data-modeling-container">
    <div class="d-m-main flex flex-row">
      <div class="d-m-left flex flex-col">
        <div class="w-full flex items-center" style="gap: 4px">
          <Tree ref="modelDataTreeRef" :isGlobalDataModeling="true" :defaultExpandedKeys="defaultExpandedKeys"
            :currentNodeKey="currentNodeKey" :treeData="modelDataList" :folderMenu="right_menuList.rightMenuList_7"
            :fileMenu="right_menuList.rightMenuList_4" @handleAddNode="handleAddModel"
            @handleMenuClick="handleMenuClick" @nodeClick="nodeClick" @moveNodeOrder="moveNodeOrder"
            @importJsonSchema="importJsonSchemaFile"></Tree>
        </div>
      </div>
      <div class="d-m-divider"></div>
      <div class="d-m-right">
        <FolderDetail v-if="isFolder" ref="folderRef" :readonly="false" :flag="'global'" :nodeInfo="selectedNodeInfo"
          @refresh="getSelfGlobalDataTree"></FolderDetail>
        <ModelDataJsonSchema v-if="isJsonSchema" type="global" ref="jsonSchemaRef" :curNode="selectedNodeInfo"
          :parentNode="selectedNodeInfo" :treeData="[]" :globalTreeData="modelDataList"
          @refresh="getSelfGlobalDataTree"></ModelDataJsonSchema>
      </div>
    </div>
    <AddOrUpdateFolder v-if="isAddOrUpdateFolder" ref="addOrUpdateFolderRef" @refresh="getSelfGlobalDataTree">
    </AddOrUpdateFolder>
    <UseCustomData v-if="isUseCustomData" ref="useCustomDataRef" @refresh="getSelfGlobalDataTree"></UseCustomData>
  </div>
</template>

<script>
import {
  getSelfGlobalDataTree,
  deleGlobalData,
  globalDataMoveTreeNode,
  importJsonSchema,
} from "@/api/myspace/model-manage-tool/model-manage";
import { mapState } from "vuex";
import Tree from "@/components/LeftTree/tree.vue";
import AddOrUpdateFolder from "./components/add-or-update-folder.vue";
import FolderDetail from "./components/folder-detail.vue";
import ModelDataJsonSchema from "./components/modelData-jsonSchema-detail-global.vue";
import UseCustomData from "./components/custom-data.vue";
export default {
  name: "DataModeling",
  data() {
    return {
      queryContent: "",
      activeName: null,
      mainVersionInfo: null,
      isFilterOpen: false,
      isAddOrUpdateFolder: false,
      isFolder: false, // 是否展示文件夹详情
      isJsonSchema: false,
      isUseCustomData: false, // 是否使用自定义数据
      selectedNodeInfo: {}, // 当前选中节点的信息
      modelDataList: [], // 模型数据
      defaultExpandedKeys: [], //树默认要展开的节点
      currentNodeKey: 0,
      filters: {
        status: "",
        tags: "",
        owner: "",
        creator: "",
        lastModifier: "",
        matchType: "include",
      },
    };
  },
  components: {
    Tree,
    AddOrUpdateFolder,
    FolderDetail,
    ModelDataJsonSchema,
    UseCustomData,
  },
  computed: {
    ...mapState({
      right_menuList: (state) => state.modelManageTool.right_menuList,
      userId: (state) => state.user.id,
      selectedNodeId: (state) => state.modelManageTool.globalData.selectedNodeId,
      expandedNodeIds: (state) => state.modelManageTool.globalData.expandedNodeIds,
    }),
    filterNum() {
      return Object.values(this.filters).filter((item) => item).length - 1;
    },
  },
  async created() {
    await this.getSelfGlobalDataTree();
    this.currentNodeKey = this.selectedNodeId;
    this.defaultExpandedKeys = this.expandedNodeIds;
    this.$nextTick(() => {
      this.$refs.modelDataTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
    })
  },
  mounted() {
  },
  methods: {
    async getSelfGlobalDataTree(newNodeId) {
      await getSelfGlobalDataTree().then((response) => {
        if (response.code == 200 && Array.isArray(response.data)) {
          this.modelDataList = response.data[0].commonTreeList;
          localStorage.setItem(
            "globalTreeData",
            JSON.stringify(this.modelDataList)
          );
          this.nodeClick(
            newNodeId ? this.recurNodeForTarget(this.modelDataList, newNodeId) :
              this.selectedNodeId ? this.recurNodeForTarget(this.modelDataList, this.selectedNodeId) :
                this.modelDataList[0])
        }
      });
    },
    // 递归获取当前树节点
    recurNodeForTarget(nodeArr, id) {
      for (let i = 0; i < nodeArr.length; i++) {
        if (nodeArr[i].id == id) {
          return nodeArr[i];
        } else {
          if (nodeArr[i].children && nodeArr[i].children.length > 0) {
            let node = this.recurNodeForTarget(nodeArr[i].children, id);
            if (node) {
              return node;
            }
          }
        }
      }
    },
    //显示筛选条件
    openFilter() {
      this.isFilterOpen = !this.isFilterOpen;
    },
    // 点击菜单项触发的事件
    handleMenuClick(menu, node) {
      switch (menu.name) {
        case "新增分类":
          this.handleAddOrUpdateFolder("add", node);
          break;
        case "新增数据模型":
          this.handleAddModel(node);
          break;
        case "使用公共数据":
          break;
        case "使用自定义数据":
          this.handleUseCustomData(node);
          break;
        case "添加子目录":
          this.handleAddOrUpdateFolder("add", node);
          break;
        case "删除":
          this.handleDeleteFile(node);
          break;
        case "导入JSON Schema文件":
          this.handleImportFile(node);
          break;
        case "编辑":
          this.handleAddOrUpdateFolder("edit", node);
          break;
      }
    },
    // 新增数据建模
    handleAddModel(data) {
      console.log("新增模型", data);
      let rep = data ? data : { id: 0, data: {} }
      this.selectedNodeInfo = rep;
      this.isFolder = false;
      this.isJsonSchema = true;
      this.$nextTick(() => {
        this.$refs.jsonSchemaRef.isAddModelData = true;
        this.$refs.jsonSchemaRef.reset(true, this.selectedNodeInfo.data);
      });
    },
    // 新增或修改文件夹
    handleAddOrUpdateFolder(sign, node) {
      this.isAddOrUpdateFolder = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdateFolderRef.init(
          sign,
          node,
          this.modelDataList,
          "global",
        );
      });
    },
    // 删除文件夹或文件
    handleDeleteFile(node) {
      const nodeTypeText = node.type == 0 ? "目录" : "数据模型";
      this.$confirm(`确定删除${nodeTypeText}  ${node.name} ?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "message-box-style",
        type: "warning",
      })
        .then(() => {
          deleGlobalData(
            node.id
          ).then((response) => {
            if (response.code == 200) {
              this.$message.success(
                this.$toolHandle.getI18nName(
                  this.$zh.setup.responseText,
                  this.$en.setup.responseText,
                  this.$i18n.locale,
                  "success"
                )
              );
              this.isFolder = false;
              this.isJsonSchema = false;
              this.selectedNodeInfo = {};
              this.$refs.modelDataTreeRef.deleteNode();
              this.getSelfGlobalDataTree();
            }
          });
        })
        .catch(() => { });
    },
    nodeClick(node) {
      if (node == undefined) {
        return;
      }
      this.selectedNodeInfo = node;
      this.currentNodeKey = node.id;
      this.$nextTick(() => {
        this.$refs.modelDataTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
      })
      this.$store.commit("modelManageTool/SET_SELECTED_NODE_ID", { moduleName: 'globalData', id: node.id })
      if (node.type == 0) {
        // 点击的文件夹
        this.isFolder = true;
        this.isJsonSchema = false;
        this.$store.commit("modelManageTool/SET_EXPANDED_NODE_IDS", { moduleName: 'globalData', idList: Array.from(new Set([...this.defaultExpandedKeys, node.id])) })
      } else {
        // 点击的文件
        this.isFolder = false;
        this.isJsonSchema = true;
        this.$nextTick(() => {
          this.$refs.jsonSchemaRef.isAddModelData = false;
          this.$refs.jsonSchemaRef.reset(false, this.selectedNodeInfo.data);
        });
      }
    },
    // 移动树节点的顺序
    moveNodeOrder(draggingNode, dropNode, dropType) {
      globalDataMoveTreeNode({
        movedNodeId: draggingNode.data.id, // 被移动节点的id
        referenceNodeId: dropNode.data.id, // 参照节点的id
        position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
        ancestors: draggingNode.data.data.ancestors, // 祖先
        folderChildrenOrder: {
          parentId:
            dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
          siblingIds:
            dropType == "inner"
              ? Array.from(dropNode.childNodes).map((item) => item.data.id)
              : Array.from(dropNode.parent.childNodes).map(
                (item) => item.data.id
              ),
        },
      }).then((response) => {
        if (response.code == 200) {
          this.$message.success(
            this.$toolHandle.getI18nName(
              this.$zh.setup.responseText,
              this.$en.setup.responseText,
              this.$i18n.locale,
              "success"
            )
          );
          this.getSelfGlobalDataTree();
        }
      });
    },
    // 使用自定义数据，弹框，选择模型，选择版本，选择数据结构
    handleUseCustomData(node) {
      this.isUseCustomData = true;
      this.$nextTick(() => {
        this.$refs.useCustomDataRef.init();
      });
    },
    // 导入jsonschema文件
    handleImportFile(node) {
      this.selectedNodeInfo = node;
    },
    // 上传文件接口
    importJsonSchemaFile(file) {
      return
      let formData = new FormData();
      formData.append("parentId", this.selectedNodeInfo.id);
      formData.append("nodeType", this.selectedNodeInfo.data.nodeType);
      formData.append(
        "modelDataType",
        this.selectedNodeInfo.data.modelDataType
      );
      formData.append("modelDataDescription", null);
      formData.append("file", file.raw);
      importJsonSchema(formData).then((response) => {
        if (response.code == 200) {
          this.$message.success(
            this.$toolHandle.getI18nName(
              this.$zh.setup.responseText,
              this.$en.setup.responseText,
              this.$i18n.locale,
              "success"
            )
          );
          this.getSelfGlobalDataTree();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.data-modeling-container {
  width: 100%;
  height: 100%;
  padding: 0 10px;
  box-sizing: border-box;

  .d-m-main {
    width: 100%;
    height: 100%;

    .d-m-left {
      width: 300px;
      height: 100%;
      flex-grow: 0;
      flex-shrink: 0;
      display: flex;
      position: relative;
      padding: 10px 10px 0 0;

      .filer-box {
        display: flex;
        flex-wrap: wrap;
        transition: all 0.5s;

        .filter-item {
          width: 50%;
          padding: 5px 5px 0 0;

          .el-radio-group {
            display: flex;
          }
        }
      }

      .tree-box {
        flex-grow: 1;
        margin-top: 5px;
        box-sizing: border-box;
      }
    }

    .d-m-divider {
      width: 1px;
      height: auto;
      flex-grow: 0;
      position: relative;
      align-self: stretch;
      background-color: var(--ui-border-color-split);
    }

    .d-m-right {
      width: 256px;
      height: 100%;
      min-width: 0px;
      flex-grow: 1;
      flex-shrink: 1;
      display: flex;
      overflow: auto;
    }
  }
}
</style>
